﻿using Handday.Erp.Transfer.Entities;
using Handday.Erp.Transfer.Enum;
using Handday.Erp.Transfer.Repositories;
using HandDay.Framework.Common.Services;
using MapsterMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Handday.Erp.Transfer.Services.Imp
{
    /// <summary>
    /// 8大交易数据统计执行服务
    /// </summary>
    public class EightTradingStatisticsExecuteService : IStatisticsExecuteService
    {
        private readonly IMapper _mapper;
        private readonly IEightTradingTransferRepository _eightTradingTransferRepository;
        private readonly IEightTradingDapperRepository _eightTradingDapperRepository;

        /// <summary>
        /// ctor
        /// </summary>
        public EightTradingStatisticsExecuteService(
            IMapper mapper,
            IEightTradingTransferRepository eightTradingTransferRepository,
            IEightTradingDapperRepository eightTradingDapperRepository)
        {
            _mapper = mapper;
            _eightTradingTransferRepository = eightTradingTransferRepository;
            _eightTradingDapperRepository = eightTradingDapperRepository;
        }

        /// <summary>
        /// 功能类型
        /// </summary>
        public ErpFeatureTypeEnum FeatureType => ErpFeatureTypeEnum.EightTrading;

        /// <summary>
        /// 执行逻辑
        /// </summary>
        /// <param name="corpId">企业编号</param>
        /// <param name="dateTime">对应日期数据</param>
        public async Task<ServiceResult> ExecuteAsync(ulong corpId, DateTimeOffset dateTime)
        {
            //减去的时间，一定要与定时任务执行间隔匹配，可尽可能保证统计数据正确
            dateTime = dateTime.AddMinutes(-10);
            var curMonth = new DateTimeOffset(dateTime.Year, dateTime.Month, 1, 0, 0, 0, TimeSpan.FromHours(8));
            var timeDic = new Dictionary<DateTimeOffset, DateTimeOffset>
            {
                {new DateTimeOffset(dateTime.Year,1,1,0,0,0,TimeSpan.FromHours(8)), new DateTimeOffset(dateTime.Year + 1,1,1,0,0,0,TimeSpan.FromHours(8)) },
                {curMonth, curMonth.AddMonths(1) },
                {curMonth.AddMonths(-1), curMonth }
            };

            //从8项交易源数据统计数据
            var list = (await _eightTradingDapperRepository.StatisticAsync(corpId, timeDic)).ToList();
            //写入或更新统计传输数据
            if (list.Any())
            {
                var customIdList = list.Select(m => m.CustomId).ToList();
                var year = list[0].Year;
                var month = list[0].Month;
                var existList = await _eightTradingTransferRepository.Where(m => m.Year == year && m.Month == month && customIdList.Contains(m.CustomId)).ToListAsync();
                var existCustomIdList = existList.Select(m => m.CustomId).ToList();
                var addList = list.Where(m => !existCustomIdList.Contains(m.CustomId)).Select(m => _mapper.Map<EightTradingTransfer>(m)).ToList();
                using (var tran = _eightTradingTransferRepository.DbContext.Database.BeginTransaction())
                {
                    await _eightTradingTransferRepository.BulkAddAsync(addList);
                    foreach (var item in existList)
                    {
                        var model = list.FirstOrDefault(m => m.CustomId == item.CustomId);
                        _mapper.Map(model, item);
                        await _eightTradingTransferRepository.UpdateAsync(item);
                    }

                    await tran.CommitAsync();
                }
            }

            return ServiceResult.Succeed();
        }
    }
}
